<?php

namespace app\admin\controller\vip;

use app\admin\model\Member;
use app\api\model\Pay;
use app\api\model\VipCard;
use app\exceptions\ApiException;
use ba\Exception;
use think\facade\Db;
use Throwable;
use app\common\controller\Backend;

/**
 * 订单管理
 */
class Order extends Backend
{
    /**
     * Order模型对象
     * @var object
     * @phpstan-var \app\admin\model\vip\Order
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['member', 'vipCard'];

    protected string|array $quickSearchField = ['id'];

    protected  $status = [0=>'待支付',1=>'待发货',2=>'已发货',3=>'已完成',4=>'已退款'];


    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\vip\Order();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where('order.status','>',0)
            ->order($order)
            ->paginate($limit);
        $res->visible(['member' => ['nickname','id'], 'vipCard' => ['name','expire_type','type']]);
        $express = (new \app\admin\model\Express())->column('delivery_name','delivery_id');

        foreach ($res as &$val){
            $val['status_text'] = $this->status[$val['status']];
            $val['express_name'] = $express[$val['express_name']] ?? "未知快递";
            $val['send_time'] = $val['send_time'] ? date("Y-m-d H:i:s",$val['send_time']) : "-";
            $val['take_time'] = $val['take_time'] ? date("Y-m-d H:i:s",$val['take_time']) : "-";
            $val['vip_code'] = $val['vip_code'] ?? '-';
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }
        $row['vip_name'] = (new VipCard())->where(['id' => $row['vip_card_id']])->field('name,image')->find();

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            //查新卡密
            $vip_code = (new \app\admin\model\vip\Code())->where(['number' => $data['vip_code']])->find();
            if(!$vip_code)   $this->error('卡密不存在');

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }

                $member = (new Member())->where(['id' => $row['member_id']])->find();
                $data['waybill_token'] = (new \ba\Order())->sendOrder($data,$member);
                $data['send_time'] = time();
                $data['vip_code'] =  $vip_code['number'];
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }


    public function refund()
    {
        $data = $this->request->post();
        if (!$data) {
            $this->error('缺少参数');
        }
        $order = $this->model->where(['id' => $data['id']])->find();
        if(!$order) $this->error('订单不存在');
        if($order['status'] == 4) $this->error('订单已退款');

        //执行退款
        try {
            Db::startTrans();
            $this->model->where(['id' => $data['id']])->update(['status' => 4, 'update_time' => time()]);
            (new Pay())->refund($order['transaction_id'], $order['out_trade_no'], $order['price'], $order['price']);
            Db::commit();
            $this->success('退款成功,请留意微信退款信息');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
    }



}
